<template>
  <div class="feedback-container">
    <el-table stripe :data="data.tableData">
      <el-table-column prop="issueType" label="问题类型"></el-table-column>
      <el-table-column
        prop="description"
        label="问题描述"
      >
        <template #default="scope">
            <el-button type="text" @click="view(scope.row.description)"
              >查看问题描述</el-button>
          </template>
    </el-table-column>
      <el-table-column prop="status" label="处理状态" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button v-if="scope.row.status == '待处理'" type="text" @click="handleFeedback(scope.row, false)">审核</el-button>
          <el-button v-else type="text" @click="handleFeedback(scope.row, true)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-self: end; margin-top: 10px">
      <el-pagination
        v-if="data.total"
        @current-change="load"
        background
        layout="total, prev, pager, next"
        :page-size="data.pageSize"
        v-model:current-page="data.pageNum"
        :total="data.total"
      />
    </div>
    
    <el-dialog title="审核" v-model="dialogVisible" width="50%" :before-close="handleBeforeClose" destroy-on-close>
      <el-form
        ref="feedbackForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        size="large"
      >
        <el-form-item label="问题类型" prop="issueType">
          <el-select v-model="formData.issueType" disabled placeholder="请选择问题类型">
            <el-option
              v-for="item in issueTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="formData.contact"
            disabled
            placeholder="请输入联系方式（选填）"
          ></el-input>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
            <el-button type="primary" @click="view(formData.description)"
            >查看问题描述</el-button>
        </el-form-item>
        <el-form-item label="处理结果" prop="backContent">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.backContent"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!isDetails" type="primary" @click="submitFeedback">确 定</el-button>
      </template>
    </el-dialog>
    
    <el-dialog
        title="问题描述"
        v-model="data.viewVisible"
        width="50%"
        :close-on-click-modal="false"
        destroy-on-close
      >
        <div
          class="editor-content-view"
          style="padding: 20px"
          v-html="data.description"
          v-if="data.description"
        ></div>
        <el-empty v-else description="暂未处理" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.viewVisible = false">关 闭</el-button>
          </span>
        </template>
      </el-dialog>
      
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { onBeforeUnmount, ref, reactive, shallowRef } from "vue";

const user = JSON.parse(localStorage.getItem('xm-user') || '{}')
const baseUrl = import.meta.env.VITE_BASE_URL

import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: user.token,
  },
  server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
const handleCreated = (editor) => {
  editorRef.value = editor;
};
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const feedbackForm = ref(null);
const formData = ref({
  issueType: "",
  contact: "",
  description: "",
  imgs: [],
  userId: "",
  backContent: ""
});
const formRules = {
  backContent: [{ required: true, message: "请输入处理结果", trigger: "blur" }],
};
const issueTypes = [
  { label: "功能问题", value: "功能问题" },
  { label: "性能问题", value: "性能问题" },
  { label: "用户体验", value: "用户体验" },
  { label: "我要投诉", value: "我要投诉" },
];
const dialogVisible = ref(false);

const handleImageRemove = (file, fileList) => {
  for (let i = 0; i < formData.value.imgs.length; i++) {
    if (formData.value.imgs[i].includes(file.name)) {
      formData.value.imgs.splice(i, 1);
    }
  }
};
const handleImageExceed = () => {
  ElMessage.warning("最多只能上传5张图片");
};
const handleFileUpload = (res) => {
  formData.value.imgs.push(res.data);
};
const submitFeedback = () => {
  formData.value.backContent = data.backContent
  feedbackForm.value.validate((valid) => {
    if (valid) {
      const userInfo = JSON.parse(localStorage.getItem("xm-user"));
      formData.value.userId = userInfo.id;

      // 提交反馈逻辑
      request.post("/feedback/audit", formData.value).then((res) => {
        load()
      });
      dialogVisible.value = false

      ElMessage.success("反馈已提交，感谢您的支持！");
    } else {
      ElMessage.error("请完善表单信息");
    }
  });
};
const isDetails = ref(false)
const handleFeedback = (row, disabled) => {
    isDetails.value = disabled
  request.get("/feedback/queryById/" + row.id).then((res) => {
    formData.value = res.data;
    data.backContent = res.data.backContent
  });
  dialogVisible.value = true;
};
const resetForm = () => {
  feedbackForm.value.resetFields();
};

const handleClose = () => {
  dialogVisible.value = false;
};

const view = (description) => {
  data.description = description;
  data.viewVisible = true;
};
// 数据列表
import request from "@/utils/request.js";

const data = reactive({
  user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  title: null,
  ids: [],
  viewVisible: false,
  backContent: null,
  description: null
});

const load = () => {
  request
    .get("/feedback/list", {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
      },
    })
    .then((res) => {
      if (res.code === "200") {
        data.tableData = res.data?.list || [];
        data.total = res.data?.total;
      } else {
        ElMessage.error(res.msg);
      }
    });
};

const add = () => {
  request.post("/forum/add", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  request.put("/forum/update", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const handleBeforeClose = ()=>{
    data.backContent = null
    dialogVisible.value = false
}
const reset = () => {
  data.title = null;
  load();
};

load();
</script>
  <style scoped>
</style>